package com.gavinandre.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerTarget implements Runnable{

	private Socket socket;



	public ServerTarget(Socket socket) {
		super();
		this.socket = socket;
	}

	@Override
	public void run() {
		//自动接收客户端发来的消息
		BufferedReader br = null;

		try {
			//创建用于接收消息的字符输入流
			br = new BufferedReader
					(new InputStreamReader(socket.getInputStream()));

			while(true){
				String clientMsg = br.readLine();//获取客户端发来的消息
				System.out.println("客户端说："+clientMsg);

				mOnUpdataListener.upDataUI(clientMsg);

				if(clientMsg.equals("byebye")){
					PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
					pw.println("byebye too");
					System.out.println("客户端已下线！");
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public Socket getSocket() {
		return socket;
	}

	public void setSocket(Socket socket) {
		this.socket = socket;
	}


	private OnUpdataListener mOnUpdataListener;

	public void setOnUpdataListener(OnUpdataListener mOnUpdataListener) {
		this.mOnUpdataListener = mOnUpdataListener;
	}

	public interface OnUpdataListener {
		void upDataUI(String  message);
	}
}
